/**
 * @author:fangxiaohua
*  @邮箱：abc2710712@qq.com
*  @qq:1295168875
*   用户业务操作操作
*/
void(function(exports){
	//数据库操作
	var dbLib = require('../lib/dbLib');
	//工具类模块
	var tools = require('../lib/toolsLib');
	
	//用户列表
	exports.userM_ulist = function(req, res){
		var pageNo=req.body.pageNo;
		var pageSize=req.body.pageSize;
		var q=req.body.q;
		var  sql=["select u.account,u.`name`,u.id,u.last_login_time,u.telephone ,GROUP_CONCAT(r.`name`) as  roleNames,GROUP_CONCAT(r.id) as  roleIds,u.status",
		          		" from t_user u left join t_user_role ur on u.id=ur.usr_id left join t_role r on ur.role_id=r.id ",
		          		" where  u.account like ? or u.`name` like ? or u.telephone like ? GROUP BY u.id"].join("");
		q=q==null?"%%":"%"+q+"%";
		var params=[q,q,q];
		dbLib.dbPageQuery(sql,pageNo,pageSize,params,function(err,result){
			res.send(result);
			return;
		});
	};
	
	//角色列表
	exports.userM_rlist=function(req,res){
		var pageNo=req.body.pageNo;
		var pageSize=req.body.pageSize;
		var q=req.body.q;
		var sql = "select id,name,description from t_role where name like ?";
		q=q==null?"%%":"%"+q+"%";
		var params=[q];
		dbLib.dbPageQuery(sql,pageNo,pageSize,params,function(err,result){
			res.send(result);
			return;
		});
	};
	
	//用户修改
	exports.userM_uEdit=function(req,res){
		var name=req.body.name;
		var telephone=req.body.telephone;
		var id=req.body.id;
		var params=[name,telephone,id];
		sql="update t_user  set name=? , telephone=? where id=?";
		dbLib.dbUpdate(sql,params,function(err,result){
			if(err){
				res.send("false");
				return;
			}
			res.send("true");
			return;
		});
	}
	
	//用户授权
	exports.userM_rUser=function(req,res){
		var id=req.body.id;
		var roleIds=req.body.roleIds;
		var  sql = "delete from t_user_role where usr_id=?";
		var params=[id];
		//删除原有的角色
		dbLib.dbDelete(sql,params,function(){
			if(roleIds){
				//添加新的角色
				var roleIdArr = roleIds.split("&");
				for(var  i = 0;i<roleIdArr.length;i++){
					console.log(roleIdArr[i]+"============");
						params=[id,roleIdArr[i]];
						sql = "insert into t_user_role(usr_id,role_id) values(?,?)";
						dbLib.dbAdd(sql,params);
				}
				res.send("true");
				return; 
			}else{
				res.send("true");
				return; 
			}
		});
	};
})( (function(){
    if(typeof exports === 'undefined') {
        window.exports = {};
        return window.exports;
    } else {
        return exports;
    }
})());